package org.jeecg.modules.business.delivery.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouse;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseService;
import org.jeecg.modules.business.delivery.entity.vo.*;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTask;
import org.jeecg.modules.business.transfer.vo.WmsMoveReceiptPage;
import org.jeecg.modules.business.transfer.vo.WmsMoveReceiptVO;
import org.jeecg.modules.dock.service.MdsDockingRepeaterService;
import org.jeecg.modules.flow.callback.enums.TransferStatusEnum;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.business.delivery.entity.WmsDeliveryTaskMaterial;
import org.jeecg.modules.business.delivery.entity.WmsDeliveryTask;
import org.jeecg.modules.business.delivery.service.IWmsDeliveryTaskService;
import org.jeecg.modules.business.delivery.service.IWmsDeliveryTaskMaterialService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


 /**
 * @Description: 调拨任务
 * @Author: jeecg-boot
 * @Date:   2023-11-22
 * @Version: V1.0
 */
 @RequiredArgsConstructor
@Api(tags="调拨任务")
@RestController
@RequestMapping("/business/wmsDeliveryTask")
@Slf4j
public class WmsDeliveryTaskController {

	private final IWmsDeliveryTaskService wmsDeliveryTaskService;

	private final IWmsDeliveryTaskMaterialService wmsDeliveryTaskMaterialService;

	private final IBasicMaterialService materialService;

	private final ISysDepartService departService;

	private final IWmsBasicWarehouseService warehouseService;

	/**
	 * 分页列表查询
	 *
	 * @param wmsDeliveryTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "调拨任务-分页列表查询")
	@ApiOperation(value="调拨任务-分页列表查询", notes="调拨任务-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<WmsDeliveryTaskPageVO>> queryPageList(WmsDeliveryTaskQueryVO wmsDeliveryTask,
															  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															  HttpServletRequest req) {
		IPage<WmsDeliveryTask> page = new Page<WmsDeliveryTask>(pageNo, pageSize);
		IPage<WmsDeliveryTaskPageVO> pageList = wmsDeliveryTaskService.listByPage(page, wmsDeliveryTask);
		List<WmsDeliveryTaskPageVO> list = pageList.getRecords();
		if(!CollectionUtil.isEmpty(list)){
			for(WmsDeliveryTaskPageVO pageVO:list){
				//设置任务的过账标识
				if(TransferStatusEnum.TRANSFER_FAIL.getCode().equals(pageVO.getTransferSapStatus())){
					pageVO.setTransferButton(true);
				}else{
					pageVO.setTransferButton(false);
				}
			}
		}
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param wmsDeliveryTaskPage
	 * @return
	 */
	@AutoLog(value = "调拨任务-添加")
	@ApiOperation(value="调拨任务-添加", notes="调拨任务-添加")
    @RequiresPermissions("business:wms_delivery_task:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody WmsDeliveryTaskPage wmsDeliveryTaskPage) {
		WmsDeliveryTask wmsDeliveryTask = new WmsDeliveryTask();
		BeanUtils.copyProperties(wmsDeliveryTaskPage, wmsDeliveryTask);
		wmsDeliveryTaskService.saveMain(wmsDeliveryTask, wmsDeliveryTaskPage.getWmsDeliveryTaskMaterialList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param wmsDeliveryTaskPage
	 * @return
	 */
	@AutoLog(value = "调拨任务-编辑")
	@ApiOperation(value="调拨任务-编辑", notes="调拨任务-编辑")
    @RequiresPermissions("business:wms_delivery_task:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody WmsDeliveryTaskPage wmsDeliveryTaskPage) {
		WmsDeliveryTask wmsDeliveryTask = new WmsDeliveryTask();
		BeanUtils.copyProperties(wmsDeliveryTaskPage, wmsDeliveryTask);
		WmsDeliveryTask wmsDeliveryTaskEntity = wmsDeliveryTaskService.getById(wmsDeliveryTask.getId());
		if(wmsDeliveryTaskEntity==null) {
			return Result.error("未找到对应数据");
		}
		wmsDeliveryTaskService.updateMain(wmsDeliveryTask, wmsDeliveryTaskPage.getWmsDeliveryTaskMaterialList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "调拨任务-通过id删除")
	@ApiOperation(value="调拨任务-通过id删除", notes="调拨任务-通过id删除")
    @RequiresPermissions("business:wms_delivery_task:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		wmsDeliveryTaskService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "调拨任务-批量删除")
	@ApiOperation(value="调拨任务-批量删除", notes="调拨任务-批量删除")
    @RequiresPermissions("business:wms_delivery_task:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.wmsDeliveryTaskService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "调拨任务-通过id查询")
	@ApiOperation(value="调拨任务-通过id查询", notes="调拨任务-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<WmsDeliveryTask> queryById(@RequestParam(name="id",required=true) String id) {
		WmsDeliveryTask wmsDeliveryTask = wmsDeliveryTaskService.getById(id);
		if(wmsDeliveryTask==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(wmsDeliveryTask);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "调拨任务物料明细通过主表ID查询")
	@ApiOperation(value="调拨任务物料明细主表ID查询", notes="调拨任务物料明细-通主表ID查询")
	@GetMapping(value = "/queryWmsDeliveryTaskMaterialByMainId")
	public Result<List<WmsDeliveryTaskMaterial>> queryWmsDeliveryTaskMaterialListByMainId(@RequestParam(name="id",required=true) String id) {
		List<WmsDeliveryTaskMaterial> wmsDeliveryTaskMaterialList = wmsDeliveryTaskMaterialService.selectByMainId(id);
		if(!CollectionUtil.isEmpty(wmsDeliveryTaskMaterialList)){
			for(WmsDeliveryTaskMaterial taskMaterial:wmsDeliveryTaskMaterialList){
				BasicMaterial material = materialService.getById(taskMaterial.getWmsBasicMaterialId());
				taskMaterial.setMaterialCode(Objects.isNull(material)?null: material.getCode());
				taskMaterial.setMaterialName(Objects.isNull(material)?null: material.getName());
			}
		}
		return Result.OK(wmsDeliveryTaskMaterialList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param wmsDeliveryTask
    */
    @RequiresPermissions("business:wms_delivery_task:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmsDeliveryTask wmsDeliveryTask) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<WmsDeliveryTask> queryWrapper = QueryGenerator.initQueryWrapper(wmsDeliveryTask, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<WmsDeliveryTask> wmsDeliveryTaskList = wmsDeliveryTaskService.list(queryWrapper);
	  List<String> ids = wmsDeliveryTaskList.stream().map(w -> w.getId()).collect(Collectors.toList());
	  List<WmsDeliveryTaskMaterial> taskMaterials = wmsDeliveryTaskMaterialService.list(new LambdaQueryWrapper<WmsDeliveryTaskMaterial>()
				.eq(WmsDeliveryTaskMaterial::getWmsDeliveryTaskId, ids));
		Map<String, List<WmsDeliveryTaskMaterial>> listMap = new HashMap<>();
		if (taskMaterials != null){
			listMap = taskMaterials.stream().collect(Collectors.groupingBy(WmsDeliveryTaskMaterial::getWmsDeliveryTaskId));
		}

        // Step.3 组装pageList
      List<WmsDeliveryTaskPage> pageList = new ArrayList<WmsDeliveryTaskPage>();
      for (WmsDeliveryTask main : wmsDeliveryTaskList) {
          WmsDeliveryTaskPage vo = new WmsDeliveryTaskPage();
          BeanUtils.copyProperties(main, vo);
          List<WmsDeliveryTaskMaterial> wmsDeliveryTaskMaterialList = listMap.get(main.getId());
          vo.setWmsDeliveryTaskMaterialList(wmsDeliveryTaskMaterialList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "调拨任务列表");
      mv.addObject(NormalExcelConstants.CLASS, WmsDeliveryTaskPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("调拨任务数据", "导出人:"+sysUser.getRealname(), "调拨任务"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("business:wms_delivery_task:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<WmsDeliveryTaskPage> list = ExcelImportUtil.importExcel(file.getInputStream(), WmsDeliveryTaskPage.class, params);
              for (WmsDeliveryTaskPage page : list) {
                  WmsDeliveryTask po = new WmsDeliveryTask();
                  BeanUtils.copyProperties(page, po);
                  wmsDeliveryTaskService.saveMain(po, page.getWmsDeliveryTaskMaterialList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 @ApiOperation(value="下查", notes="下查")
	 @GetMapping(value = "/underList")
	 public Result<List<DeliveryUnderListVO>> underList(@RequestParam(name="taskId") String taskId,@RequestParam(name="type",required = false) String type) {

		 List<DeliveryUnderListVO> list=wmsDeliveryTaskService.underList(taskId,type);
		return Result.OK(list);
	 }

	 @ApiOperation(value="条料调拨因入移库单-从入库任务中获取移库物料信息", notes="条料调拨因入移库单-从入库任务中获取移库物料信息")
	 @PostMapping("/move/getMoveMaterialFormInTask")
	 public Result<WmsMoveReceiptVO> getMoveMaterialFormInTask(@Valid @RequestBody NeedMoveMaterialVO needMoveMaterialVO){
		 WmsMoveReceiptVO receiptVO=wmsDeliveryTaskService.getMoveMaterialFormInTask(needMoveMaterialVO);
		 return Result.ok(receiptVO);
	 }

	 @ApiOperation(value="条料调拨因出移库单-从出库任务中获取移库物料信息", notes="条料调拨因出移库单-从出库任务中获取移库物料信息")
	 @PostMapping("/move/getMoveMaterialFormOutTask")
	 public Result<WmsMoveReceiptVO> getMoveMaterialFormOutTask(@Valid @RequestBody NeedMoveMaterialVO needMoveMaterialVO){
		 WmsMoveReceiptVO receiptVO=wmsDeliveryTaskService.getMoveMaterialFormOutTask(needMoveMaterialVO);
		 return Result.ok(receiptVO);
	 }

	 /**
	  * 条料调拨因出移库单-叫料架
	  * @return
	  */
	 @ApiOperation(value="条料调拨因出移库单-叫料架", notes="条料调拨因出移库单-叫料架")
	 @PostMapping("/move/askMaterialRack")
	 public Result<Void> askMaterialRack(@Valid @RequestBody AskMaterialRackVO askMaterialRackVO){

		 wmsDeliveryTaskService.askMaterialRack(askMaterialRackVO);
		return Result.ok();
	 }

	 /**
	  * 调拨任务过账
	  * @return
	  */
	 @ApiOperation(value = "调拨任务过账", notes = "调拨任务过账")
	 @PostMapping("/deliveryTaskTransfer")
	 public Result<Void> deliveryTaskTransfer(@RequestParam(value = "taskId")String taskId){
		 List<String> errorList=wmsDeliveryTaskService.deliveryTaskTransfer(taskId);
		 if(CollectionUtil.isEmpty(errorList)){
			 return Result.ok("过账成功");
		 }else {
			 return Result.error("过账失败: SAP报错信息为"+StrUtil.join(",",errorList));
		 }
	 }

}
